package com.softeem.hbsm_video.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.softeem.hbsm_video.dto.VideoDTO;
import com.softeem.hbsm_video.entity.*;
import com.softeem.hbsm_video.service.*;
import com.softeem.hbsm_video.utils.QiniuOssUtils;
import com.softeem.hbsm_video.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;
import java.util.UUID;

/**
 * @author ZhouYu
 * @version 1.0
 * 视频业务接口
 */
@RequestMapping("/video")
@RestController
public class VideoController {

    @Autowired
    private VideoService videoService;
    @Autowired
    private UserService userService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private FavoriteService favoriteService;

    @GetMapping("/list")
    public R list(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "5") Integer limit){
        //分页查询视频资源
        List<Video> list = videoService.list(new Page<Video>(page, limit));
        list.forEach(v->{
            // 获取作者id
            Integer uid = v.getUid();
            // 获取频道id
            Integer cid = v.getCid();
            //根据作者id查询作者
            User user = userService.getById(uid);
            Category category = categoryService.getById(cid);
            //将视频的作者和频道设置到视频对象中
            v.setUser(user);
            v.setCategory(category);
        });
        //查询总记录数
        long count = videoService.count();
        return R.ok("查询成功").setData(list).setCount(count);
    }

    /**
     * 查询所有频道
     * @return
     */
    @RequestMapping("/categories")
    public R listCategories(){
        List<Category> list = categoryService.list();
        return R.ok("查询成功").setData(list);
    }

    /**
     * 文件上传
     * @param file
     * @return
     */
    @RequestMapping("/upload")
    public R upload(MultipartFile file){
        try {
            //对本次上传的文件生成随机key(UUID)
            String key = UUID.randomUUID().toString();
            //获取文件输入流
            InputStream inputStream = file.getInputStream();
            //创建OSS工具类对象
            QiniuOssUtils utils = new QiniuOssUtils();
            //将文件流上传到七牛OSS
            String url = utils.upload(inputStream, key);
            return R.ok("上传成功").setData(url);
        } catch (Exception e) {
            return R.fail("上传失败");
        }
    }

    /**
     * 视频添加
     * @param video
     * @return
     */
    @RequestMapping("/add")
    public R add(Video video){
        boolean b = videoService.save(video);
        return b ? R.ok("添加成功") : R.fail("添加失败");
    }

    /**
     * 视频编辑
     * @param video
     * @return
     */
    @Transactional
    @PostMapping("/update")
    public R update(@RequestBody VideoDTO video) {
        String title = video.getTitle(); // 获取视频标题

        if (title != null && !title.isEmpty()) {
            // 根据视频标题查询视频对象
            Video byTitle = videoService.findByTitle(title);

            if (byTitle == null) {
                return R.fail("视频不存在");
            }

            String author = video.getAuthor();
            if (author != null && !author.isEmpty()) {
                List<User> userList = userService.list(new LambdaQueryWrapper<User>().eq(User::getUsername, author));
                if (userList.isEmpty()) {
                    User user = new User();
                    user.setUsername(author);
                    user.setPassword("123456");
                    boolean isSaved = userService.save(user);
                    if (isSaved) {
                        byTitle.setUid(user.getId());
                    }
                }
                video.setUid(userList.get(0).getId());
            }

            String Cname = video.getCategory(); // 频道分类 category
            if (Cname != null && !Cname.isEmpty()) {
                List<Category> categoryList = categoryService.list(new LambdaQueryWrapper<Category>().eq(Category::getName, Cname));
                if (categoryList.isEmpty()) {
                    Category category = new Category();
                    category.setName(Cname);
                    boolean isSaved = categoryService.save(category);
                    if (isSaved) {
                        byTitle.setCid(category.getId());
                    }
                }
                video.setCid(categoryList.get(0).getId());
            }

            // 复制属性时忽略releasetime, author, category属性
            BeanUtil.copyProperties(video, byTitle, "releasetime", "author", "category");

            boolean updateResult = videoService.updateByTitle(byTitle);
            return updateResult ? R.ok("修改成功") : R.fail("修改失败");
        }
        return R.fail("修改失败");
    }

    /**
     * 视频删除
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    public R delById(Integer id){
        //根据id删除视频评论
        boolean b = commentService.remove(Wrappers.query(Comment.class).eq("vid", id));
        QiniuOssUtils utils  = new QiniuOssUtils();
        //获取视频url地址
        Video video = videoService.getById(id);
        String url = video.getUrl();
        //截取视频的文件名作为key
        String key = url.substring(url.lastIndexOf("/")+1);
        //根据key删除OSS视频文件
        utils.delete(key);

        //删除封面图
        String coverimg = video.getCoverimg();
        key = coverimg.substring(coverimg.lastIndexOf("/")+1);
        utils.delete(key);

        return videoService.removeById(id) ? R.ok("删除成功") : R.fail("删除失败");
    }


    /**
     * 按关键词搜索视频
     * @param page
     * @param limit
     * @param keyword
     * @return
     */
    @GetMapping("/search")
    public R search(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "5") Integer limit,
            @RequestParam(required = false) String keyword
    ) {
        // 分页查询视频资源，按关键词过滤
        Page<Video> pageRequest = new Page<>(page, limit);
        QueryWrapper<Video> queryWrapper = new QueryWrapper<>();
        if (keyword != null && !keyword.isEmpty()) {
            queryWrapper.like("title", keyword);
        }
        List<Video> list = videoService.list(pageRequest, queryWrapper);

        list.forEach(v -> {
            // 获取作者id
            Integer uid = v.getUid();
            // 获取频道id
            Integer cid = v.getCid();
            // 根据作者id查询作者
            User user = userService.getById(uid);
            Category category = categoryService.getById(cid);
            // 将视频的作者和频道设置到视频对象中
            v.setUser(user);
            v.setCategory(category);
        });
        // 查询总记录数，按关键词过滤
        long count = videoService.count(queryWrapper);
        return R.ok("查询成功").setData(list).setCount(count);
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @PostMapping("/deleteBatch")
    public R deleteBatch(@RequestBody List<Integer> ids) {
        // 先删除与视频相关的评论记录
        commentService.remove(new QueryWrapper<Comment>().in("vid", ids));
        // 先删除与视频相关的收藏记录
        favoriteService.remove(new QueryWrapper<Favorite>().in("vid", ids));

        // 删除与视频关联的OSS文件
        QiniuOssUtils utils = new QiniuOssUtils();
        ids.forEach(id -> {
            Video video = videoService.getById(id);
            String url = video.getUrl();
            String key = url.substring(url.lastIndexOf("/") + 1);
            utils.delete(key);

            String coverimg = video.getCoverimg();
            key = coverimg.substring(coverimg.lastIndexOf("/") + 1);
            utils.delete(key);
        });

        // 然后删除视频记录
        boolean success = videoService.removeByIds(ids);
        if (success) {
            return R.ok("批量删除成功");
        } else {
            return R.fail("批量删除失败");
        }
    }
}
